package cn.doitedu.webserver.dao;

import cn.doitedu.webserver.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.Properties;


@Repository
public class UserDaoImpl implements UserDao {

    Connection conn = null;
    Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);

    public UserDaoImpl() throws SQLException {
        Properties props = new Properties();
        props.setProperty("user","root");
        props.setProperty("password","123456");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/realtimedw?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&useSSL=false", props);
        logger.warn("数据库连接构造成功");
    }


    @Override
    public User findUserByAccount(User user) {

        try {
            PreparedStatement ps = conn.prepareStatement("select id,account,password,member_level from user where account = ?");
            ps.setString(1,user.getAccount());

            ResultSet rs = ps.executeQuery();


            User u = null;
            while(rs.next()){
                u = new User();
                u.setId(rs.getInt(1));
                u.setAccount(rs.getString(2));
                u.setPassword(rs.getString(3));
                u.setMemberLevel(rs.getString(4));
            }

            return u;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        return null;
    }

    @Override
    public boolean insertUser(User user) throws SQLException {
        PreparedStatement ps = conn.prepareStatement("insert into user (account,password,member_level,phonenbr) values(?,?,?,?)");
        ps.setString(1,user.getAccount());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getMemberLevel());
        ps.setString(4,user.getPhone());

        boolean res = ps.execute();
        System.out.println("dao 中：res  = " + res);
        return !res;
    }
}
